from minio import Minio
from minio.error import S3Error
import json

# 初始化 MinIO 客户端
endpoint = "192.168.50.103:9000"  # 替换为你的 MinIO 服务地址
secure = False  # 如果是 HTTP 使用 False
client = Minio(
    endpoint,
    access_key="gytZQZdmOhe2JZc6yr1k",  # 替换为你的访问密钥
    secret_key="TGs7wgbxOuvYCFZ2D5jXuoCOBTlehxJNnODXn0id",  # 替换为你的密钥
    secure=secure
)

bucket_name = "pic"
object_name = "kb/test1.jpg"  # 定义对象存储名称
file_path = "testdata/icons/chat gpt.png"  # 本地文件路径

# 检查存储桶是否存在，如果不存在则创建
try:
    if not client.bucket_exists(bucket_name):
        client.make_bucket(bucket_name)
    print(f"Bucket '{bucket_name}' is ready.")
except S3Error as e:
    print(f"Error checking/creating bucket: {e}")

# 上传文件
try:
    client.fput_object(bucket_name, object_name, file_path)
    print(f"'{object_name}' is successfully uploaded.")
except S3Error as e:
    print(f"Error uploading file: {e}")

# 设置存储桶为公开访问
try:
    policy = {
        "Version": "2012-10-17",
        "Statement": [
            {
                "Effect": "Allow",
                "Principal": {"AWS": ["*"]},
                "Action": ["s3:GetObject"],
                "Resource": [f"arn:aws:s3:::{bucket_name}/*"]
            }
        ]
    }
    policy_json = json.dumps(policy)
    client.set_bucket_policy(bucket_name, policy_json)
    print(f"Bucket '{bucket_name}' is now publicly accessible.")
except S3Error as e:
    print(f"Error setting bucket policy: {e}")

# 构造对象的公开 URL
protocol = "http" if not secure else "https"
object_url = f"{protocol}://{endpoint}/{bucket_name}/{object_name}"
print(f"Public URL: {object_url}")